package com.zhouyu.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description 代表Spring容器
 * @Author dangxianyue
 * @Date 2024/3/26 10:13
 */
public class MyApplicationContext {

    private Class configClass;

    // BeanDefinition容器 beanName -> BeanDefinition
    private Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

    // Bean容器
    private Map<String, Object> singletonObjects = new ConcurrentHashMap<>();

    // BeanPostProcessor容器
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();


    public MyApplicationContext(Class configClass) {
        this.configClass = configClass;

        // 扫描--->BeanDefinition--->beanDefinitionMap
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String path = componentScanAnnotation.value();// 扫描路径 com.zhouyu.service

            path = path.replace(".", "/");// 相对路劲 com/zhouyu/service

            ClassLoader classLoader = MyApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);

            File file = new File(resource.getFile());// 拿到编译后的绝对路径
            // System.out.println(file);// D:\JavaProject\demo\test\production\MySpring\com\zhouyu\service

            if (file.isDirectory()) {
                final File[] files = file.listFiles();
                for (File f : files) {
                    String fileName = f.getAbsolutePath();
                    // System.out.println(fileName);

                    if (fileName.endsWith(".class")) {
                        // 简单示例得到类权限名，实际上不可能是这样子
                        String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                        className = className.replace("\\", ".");
                        // System.out.println(className);// com.zhouyu.service.UserService

                        try {
                            // 加载类
                            Class<?> clazz = classLoader.loadClass(className);

                            if (clazz.isAnnotationPresent(Component.class)) {
                                // 判断是否由BeanPostProcessor.class派生的
                                if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                    BeanPostProcessor beanPostProcessor = (BeanPostProcessor) clazz.newInstance();
                                    beanPostProcessorList.add(beanPostProcessor);
                                }


                                // beanName
                                Component component = clazz.getAnnotation(Component.class);
                                String beanName = component.value();
                                if (beanName.equals("")) {
                                    // 默认是首字母小写作为beanName，如OrderService的名称就自动设置为orderService
                                    beanName = Introspector.decapitalize(clazz.getSimpleName());
                                }

                                // BeanDefinition
                                BeanDefinition beanDefinition = new BeanDefinition();
                                beanDefinition.setType(clazz);

                                String scope;
                                if (clazz.isAnnotationPresent(Scope.class)) {
                                    Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
                                    scope = !scopeAnnotation.value().equals("") ? scopeAnnotation.value() : Scope.SINGLETON;
                                } else {
                                    // 默认没有@Scope注解是单例
                                    scope = Scope.SINGLETON;
                                }
                                beanDefinition.setScope(scope);

                                beanDefinitionMap.put(beanName, beanDefinition);
                            }

                        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }

        // 扫描完实例化单例Bean（实际上可能会有懒加载）
        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals(Scope.SINGLETON)) {
                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }

        }
    }

    /**
     * 创建bean Userservice.class--->无参的构造方法--->对象---->依赖注入--->Bean对象
     * @param beanName
     * @param beanDefinition
     * @return
     */
    private Object createBean(final String beanName, final BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getType();
        try {
            Object instance = clazz.getConstructor().newInstance();

            // 依赖注入（简单版：这里简单演示byName注入）
            for (Field f : clazz.getDeclaredFields()) {
                if (f.isAnnotationPresent(Autowired.class)) {
                    f.setAccessible(true);
                    f.set(instance, getBean(f.getName()));// 以field的名称作为beanName
                }
            }

            // BeanNameAware回调
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware)instance).setBeanName(beanName);
            }

            // 初始化前置处理
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(beanName, instance);
            }

            // 初始化InitializingBean
            if (instance instanceof InitializingBean) {
                ((InitializingBean)instance).afterPropertiesSet();
            }

            // 初始化后置处理
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(beanName, instance);
            }

            return instance;
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }


    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null) {
            throw new NullPointerException();
        } else {
            String scope = beanDefinition.getScope();
            if (scope.equals(Scope.SINGLETON)) {
                // 单例
                Object bean = singletonObjects.get(beanName);
                if (bean == null) {
                    bean = createBean(beanName, beanDefinition);
                    singletonObjects.put(beanName, bean);
                }
                return bean;
            } else {
                // 多例
                return createBean(beanName, beanDefinition);
            }
        }

    }
}
